package com.xiaoxx.controller.oss;


import com.xiaoxx.common.result.R;
import com.xiaoxx.common.result.RType;
import com.xiaoxx.enums.AliyunRType;
import com.xiaoxx.utils.FileUploadUtil;
import com.xiaoxx.utils.OssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @author :HX
 * @date : 2023/7/11
 */
@RestController
@Api(value = "AliOssController", tags = "AliYun --> OSS文件管理")
@RequestMapping("/alioss")
public class AliYunOssController {
    @Resource
    private OssUtil ossUtil;

    /**
     * 文件上传
     *
     * @param file
     * @param filePath
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ApiOperation("OSS-文件上传,可在指定路径后追加子路径,以/结尾，返回完整可访问当前服务内网访问OSS的完整URL")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "filePath", value = "文件路径,必须指定开头目录,可使用二级目录,三级目录等等,如头像上传(" + "\r\n" +
                    "图片=image/" + "\r\n" +
                    "头像=image/head/  (二级目录)" + "\r\n" +
                    "音乐=music/" + "\r\n" +
                    "视频=video/" + "\r\n" +
                    "文档=doc/" + "\r\n" +
                    "任意文件=file/" + "\r\n" +
                    ")", required = true)
    })
    public R<String> upload(@RequestParam("file") MultipartFile file, @RequestParam("filePath") String filePath) {
        // 验证文件格式及路径，并获取文件上传路径, file.getOriginalFilename()=原文件名
        R<String> rfilePath = FileUploadUtil.getPath(filePath, file.getOriginalFilename());
        if (!rfilePath.getCode().equals(RType.SYS_SUCCESS.getValue())) {
            return R.error(AliyunRType.FILE_UPLOAD_FAILED.getValue(), rfilePath.getMsg());
        }
        //
        String fileName = rfilePath.getData();
        try {
            // 上传到OSS,返回访问地址
            String path = ossUtil.upload(filePath, fileName, file.getInputStream());
            return R.success(path);
        } catch (Exception e) {
            return R.error(AliyunRType.FILE_UPLOAD_FAILED);
        }
    }
}
